from browser import document
from browser import html
from browser import ajax
from browser import alert
from browser import window

import json

userName = document["inputUsername"]
inputUserGroup = document["inputUserGroup"]
inputUserRemask = document["inputUserRemask"]
displayUserInfo = document["displayUserInfo"]

fromdata = document.baseURI.split("?")[1]
dataItem = {}
optionChecked = {}

for item in fromdata.split("&"):
    k = item.split("=")[0]
    v = item.split("=")[1]

    dataItem[k] = v

def updateOptions(req):
    data = json.loads(req.text)
    if data["Code"] == 0:
        for item in  data["Data"]:
            option = html.OPTION(item["Names"])
            option.value = item["Id"]

            if str(item["Id"]) in optionChecked:
                option.selected  = True

            inputUserGroup <= option

def queryUserInfo(req):
    if req.status == 200:
        data = json.loads(req.text)

        if 0 == data["Code"]:
            for checked in (data["Data"][0]["GroupIDs"]).split(":"):
                optionChecked[checked] = True

            request = ajax.Ajax()
            request.bind("complete", updateOptions)
            request.open("GET", "/showGroups", False)
            request.send()

            userName.value = data["Data"][0]["Username"]
            inputUserRemask.value = data["Data"][0]["Remask"]


request = ajax.Ajax()
request.bind("complete", queryUserInfo)
request.open("GET", "/showUsers?username="+dataItem["username"], False)
request.send()

def updateUserDatas(req):
    # data = json.loads(req.text)
    # displayUserInfo.clear()
    # displayUserInfo <= html.B(data["msg"])
    alert(req.text)
    window.location.href = "./index.html?page=users"

def updateUser(ev):
    usernameVal = userName.value
    userRemask = inputUserRemask.value
    userGroupVal = ""

    for item in inputUserGroup:
        if item.selected:
            if userGroupVal == "":
                userGroupVal = str(item.value)
                continue

            userGroupVal = userGroupVal + ":" + str(item.value)

    reqData = {}
    reqData["username"] = usernameVal
    reqData["group"] = userGroupVal
    reqData["remask"] = userRemask


    request = ajax.Ajax()
    request.bind("complete", updateUserDatas)
    request.open("POST", "/manageUsers", False)
    request.send(reqData)

    userName.value = ""
    inputUserRemask.value = ""

saveUserInfo = document["saveUserInfo"]
saveUserInfo.bind("click",updateUser)